import os
import pandas as pd
from datetime import datetime as dt
from concurrent.futures import ThreadPoolExecutor


class Image():
    def __init__(self, name, tag, _id=None) -> None:
        self.name = name
        self.tag = tag
        self.id = _id
        self.res = ""
    
    def remove(self, by_id=False):
        if by_id and self.id:
            res = os.popen("docker rmi -f %s" % self.id ).read()
        else:
            res = os.popen("docker rmi %s:%s" % (self.name, self.tag)).read()
        if self._check_error(res):
            return False
        return True
    
    @staticmethod
    def _check_error(res, includes=['error', 'failed']):
        for i in includes:
            if i in res.lower():
                return True
        return False


def get_images(cmd="docker images"):
    res = os.popen(cmd).read()
    images = []
    for line in res.split("\n"):
        tmp = [i for i in line.split(" ") if i]
        if len(tmp) < 2:
            continue
        if tmp[2].lower() == 'image':continue
        images.append(Image(tmp[0], tmp[1], tmp[2]))
    return images

def remove_imgs(imgs):
    count = 0
    for i in range(len(imgs)):
        for img in imgs:
            if img.remove(by_id=True):
                count += 1
        if len(imgs) == count:
            break
